package com.matrix.gallery.ui.wallpaper

import android.view.View.GONE
import android.view.View.VISIBLE
import androidx.activity.viewModels
import androidx.core.view.ViewCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.matrix.basecore.arouter.ARouterUtils
import com.matrix.basecore.base.BaseActivity
import com.matrix.basecore.constant.Constant
import com.matrix.basecore.utils.SpacesItemDecoration
import com.matrix.basecore.utils.glide.GlideUtil
import com.matrix.gallery.R
import com.matrix.gallery.databinding.ActivityPhoneComputerBinding
import com.matrix.gallery.net.GalleryResult
import com.matrix.gallery.ui.wallpaper.adapter.BannerPagerAdapter
import com.matrix.gallery.ui.wallpaper.adapter.RVComputerAdapter
import com.matrix.gallery.ui.wallpaper.adapter.RVGalleryAdapter
import com.matrix.gallery.ui.wallpaper.bean.PhoneBean
import com.matrix.gallery.ui.wallpaper.bean.PhoneComputerTypeBean
import com.matrix.gallery.ui.wallpaper.bean.WallpaperBean
import com.matrix.gallery.ui.wallpaper.fragment.PageFragment
import com.matrix.gallery.ui.wallpaper.transformer.ZoomPageTransformer
import com.matrix.gallery.ui.wallpaper.viewmodel.PhoneComputerVM
import kotlinx.coroutines.runBlocking

@Route(path = Constant.ARouterPath.PhoneComputerActivityPath)
class PhoneComputerActivity : BaseActivity<ActivityPhoneComputerBinding>() {

    private val vm: PhoneComputerVM by viewModels()
    var categoryList: MutableList<PhoneComputerTypeBean.Category> = mutableListOf()
    private lateinit var vpAdapter: BannerPagerAdapter
    private lateinit var mfragment: MutableList<Fragment>;
    private lateinit var type: String
    private lateinit var adapter: RVGalleryAdapter
    private lateinit var comAdapter: RVComputerAdapter

    private var verticals: MutableList<PhoneBean.Vertical> = mutableListOf()
    private var wallpaper: MutableList<WallpaperBean.Wallpaper> = mutableListOf()

    private var skip: Int = 0
    private lateinit var category: PhoneComputerTypeBean.Category

    override fun getViewBinding(): ActivityPhoneComputerBinding {
        return ActivityPhoneComputerBinding.inflate(layoutInflater)
    }

    override fun initView() {
        type = intent.getStringExtra(Constant.ARouterString.TYPE).toString()
        mViewBinding.titleBar.ivRight.setImageResource(R.mipmap.icon_hide)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            mViewBinding.sbhv.visibility = VISIBLE
            return@setOnApplyWindowInsetsListener insets
        }
        var glm = GridLayoutManager(this, if (type == Constant.Value.PHONE) 3 else 2)
        mViewBinding.recyclerview.layoutManager = glm
        adapter = RVGalleryAdapter(R.layout.wallpaper_gallery_layout, verticals)
        comAdapter = RVComputerAdapter(R.layout.wallpaper_computer_layout, wallpaper)
        mViewBinding.recyclerview.addItemDecoration(SpacesItemDecoration(16, 8, 8, 0))
        if (type == Constant.Value.PHONE) {
            mViewBinding.titleBar.tvTitle.text = getString(R.string.phone_wallpaper)
            mViewBinding.recyclerview.adapter = adapter
        } else {
            mViewBinding.titleBar.tvTitle.text = getString(R.string.computer_wallpaper)
            mViewBinding.recyclerview.adapter = comAdapter
        }

    }

    override fun initData() {
        if (type == Constant.Value.PHONE) {
            vm.phoneWallpaper().observe(
                this
            ) { value ->
                if (value.code == GalleryResult.SUCCESS) {
                    value.t?.let {
                        categoryList.addAll(it as List<PhoneComputerTypeBean.Category>)
                        categoryList.addAll(it)
                        initViewpagerData()
                    }
                } else {
                    ToastUtils.showShort(value.msg)
                }
            }
        } else {
            vm.computerWallpaper().observe(
                this
            ) { value ->
                if (value.code == GalleryResult.SUCCESS) {
                    value.t?.let {
                        categoryList.addAll(it as List<PhoneComputerTypeBean.Category>)
                        categoryList.addAll(it)
                        initViewpagerData()
                    }
                } else {
                    ToastUtils.showShort(value.msg)
                }
            }
        }
    }

    private fun initViewpagerData() {
        mfragment = mutableListOf()
        for (i in 0..2) {
            for (j in 0..<categoryList.size) {
                mfragment.add(PageFragment(categoryList[j]))
            }
        }
        vpAdapter = BannerPagerAdapter(supportFragmentManager, mfragment)
        mViewBinding.viewpager.setOffscreenPageLimit(4)
        mViewBinding.viewpager.adapter = vpAdapter
        mViewBinding.viewpager.setPageTransformer(false, ZoomPageTransformer(0.8f))
        mViewBinding.viewpager.currentItem = categoryList.size - 1
    }

    override fun initListener() {
        mViewBinding.titleBar.ivBack.setOnClickListener {
            finish()
        }
        mViewBinding.titleBar.ivRight.setOnClickListener {
            if (mViewBinding.rlVpLayout.visibility == GONE) {
                mViewBinding.titleBar.ivRight.setImageResource(R.mipmap.icon_hide)
                mViewBinding.rlVpLayout.visibility = VISIBLE
            } else {
                mViewBinding.titleBar.ivRight.setImageResource(R.mipmap.icon_show)
                mViewBinding.rlVpLayout.visibility = GONE
            }
        }
        mViewBinding.viewpager.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                category = categoryList[position % categoryList.size]
                GlideUtil.loadBlurImage(
                    category.cover,
                    this@PhoneComputerActivity,
                    mViewBinding.ivCover,
                    1,
                    4,
                    R.mipmap.icon_default_bg
                )
                skip = 0
                if (type == Constant.Value.PHONE) {
                    verticals.clear()
                    adapter.setList(verticals)
                    getAllWallpaper(category)
                } else {
                    wallpaper.clear()
                    comAdapter.setList(wallpaper)
                    getAllWallpaper(category)
                }
            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        })
        adapter.loadMoreModule.setOnLoadMoreListener({
            skip += 12
            getAllWallpaper(category)
        })

        comAdapter.loadMoreModule.setOnLoadMoreListener({
            skip += 12
            getAllWallpaper(category)
        })
        adapter.setOnItemClickListener({ adapter, view, position ->
            runBlocking {
                var data: ArrayList<String> = transitionData(verticals, wallpaper)
                ARouterUtils.startPreviewActivityPath(data, position)
            }
        })
        comAdapter.setOnItemClickListener({ adapter, view, position ->
            runBlocking {
                var data: ArrayList<String> = transitionData(verticals, wallpaper)
                ARouterUtils.startPreviewActivityPath(data, position)
            }
        })
    }

    private fun getAllWallpaper(category: PhoneComputerTypeBean.Category) {
        if (type == Constant.Value.PHONE) {
            vm.getAllWallpaper(category.id, skip).observe(this, { value ->

                if (value.code == GalleryResult.SUCCESS) {
                    value.t?.let {
                        verticals.addAll(it as List<PhoneBean.Vertical>)
                        adapter.setList(verticals)
                        adapter.loadMoreModule.loadMoreComplete()
                        if (it.size < 12) {
                            comAdapter.loadMoreModule.loadMoreEnd()
                        }
                    }
                } else {
                    ToastUtils.showShort(value.msg)
                }
            })
        } else {
            vm.getComputerWallpaper(category.id, skip).observe(this, { value ->
                value.let {
                    if (value.code == GalleryResult.SUCCESS) {
                        value.t?.let {
                            wallpaper.addAll(it as List<WallpaperBean.Wallpaper>)
                            comAdapter.setList(wallpaper)
                            comAdapter.loadMoreModule.loadMoreComplete()
                            if (it.size < 12) {
                                comAdapter.loadMoreModule.loadMoreEnd()
                            }
                        }
                    } else {
                        ToastUtils.showShort(value.msg)
                    }


                }
            })
        }
    }


    private fun transitionData(
        verticals: MutableList<PhoneBean.Vertical>,
        wallpaper: MutableList<WallpaperBean.Wallpaper>,
    ): ArrayList<String> {
        var list: ArrayList<String> = arrayListOf()
        if (verticals.size > 0) {
            for (item in verticals) {
                list.add(item.img)
            }
        }
        if (this.wallpaper.size > 0) {
            for (item in wallpaper) {
                list.add(item.thumb)
            }
        }
        return list
    }
}